﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.IO.Compression;
using System.Web;
using System.Drawing;
using System.Threading;
using System.Text.RegularExpressions;

namespace Blank.Extends
{
    public static class HttpWebExtends
    {
        /// <summary>
        /// 对流进行解压操作
        /// </summary>
        /// <param name="response"></param>
        /// <returns></returns>
        private static Stream DeCompress(this HttpWebResponse response)
        {
            if (response == null)
                return null;
            else if (response.ContentEncoding.Equals("gzip", StringComparison.OrdinalIgnoreCase))
            {
                return new GZipStream(response.GetResponseStream(), CompressionMode.Decompress);
            }
            else if (response.ContentEncoding.Equals("deflate", StringComparison.OrdinalIgnoreCase))
            {
                return new DeflateStream(response.GetResponseStream(), CompressionMode.Decompress);
            }
            else
                return response.GetResponseStream();
        }
        /// <summary>
        /// 读取HTTP响应中的字符串
        /// </summary>
        /// <param name="response"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static string ReadString(this HttpWebResponse response, Encoding encoding)
        {
            return response.ReadString(ref encoding);
        }
        /// <summary>
        /// 读取HTTP响应中的字符串
        /// </summary>
        /// <param name="response"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static string ReadString(this HttpWebResponse response, ref Encoding encoding)
        {
            byte[] bytes = response.ReadBytes();
            if (encoding == null)
            {
                #region 获取和设置当前请求页面的编码格式
                if (!string.IsNullOrEmpty(response.CharacterSet))
                {
                    encoding = Encoding.GetEncoding(response.CharacterSet);
                }
                else
                {
                    string result = Encoding.Default.GetString(bytes);
                    Match match = Regex.Match(result, "<meta([^<]*)charset=([^<]*)[\"']", RegexOptions.IgnoreCase);
                    string charset = (match.Groups.Count > 1 ? match.Groups[2].Value.ToLower().Trim() : string.Empty);

                    if (charset.Length > 2)
                    {
                        try
                        {
                            if (charset.IndexOf(" ") > 0)
                            {
                                charset = charset.Substring(0, charset.IndexOf(" "));
                            }
                            encoding = Encoding.GetEncoding(charset.Replace("\"", "").Replace("'", "").Replace(";", "").Replace("iso-8859-1", "gbk").Trim());
                        }
                        catch
                        {
                            encoding = Encoding.UTF8;
                        }
                    }
                    else
                        encoding = Encoding.UTF8;
                }

                #endregion
            }
            return encoding.GetString(bytes);
        }
        /// <summary>
        /// 读头像
        /// </summary>
        /// <param name="response"></param>
        /// <returns></returns>
        public static Image ReadImage(this HttpWebResponse response)
        {
            using (Stream stream = response.DeCompress())
            {
                return Image.FromStream(stream);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="response"></param>
        /// <returns></returns>
        public static byte[] ReadBytes(this HttpWebResponse response)
        {
            List<byte> ls = new List<byte>();
            using (Stream stream = response.DeCompress())
            {
                byte[] bytes = new byte[2048];
                int num = 0;
                while ((num = stream.Read(bytes, 0, bytes.Length)) > 0)
                {
                    ls.AddRange(bytes);
                }
            }
            return ls.ToArray();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="request"></param>
        /// <param name="OnGetResponseCompleted"></param>
        /// <param name="webTimeOut"></param>
        public static void BeginGetResponse(this HttpWebRequest request, Action<HttpWebResponse> OnGetResponseCompleted, int webTimeOut = 120000)
        {
            if (request != null)
            {
                object[] asyncResults = new object[] { request, OnGetResponseCompleted };
                request.BeginGetResponse(new AsyncCallback(EndReadGetResponse), asyncResults);
                WaitCallback callBack = delegate(object obj)
                {
                    Thread.Sleep(webTimeOut);
                    HttpWebRequest request1 = obj as HttpWebRequest;
                    if (obj != null)
                    {
                        try
                        {
                            request1.Abort();
                        }
                        catch
                        {
                        }
                    }
                };
                ThreadPool.QueueUserWorkItem(callBack, request);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="asyncResult"></param>
        private static void EndReadGetResponse(IAsyncResult asyncResult)
        {
            object[] asyncStates = asyncResult.AsyncState as object[];
            HttpWebRequest request = null;
            Action<HttpWebResponse> callback = null;
            try
            {
                request = asyncStates[0] as HttpWebRequest;
                callback = asyncStates[1] as Action<HttpWebResponse>;
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);
                if (callback != null)
                    callback(response);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (request != null)
                {
                    request.Abort();
                }
            }
        }
    }
}
